package com.jzqf.canvas;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.jzqf.wheel.MathUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CanvasView extends View {
    private final String TAG = CanvasView.class.getName();

    public CanvasView(Context context) {
        super(context);
    }


    public CanvasView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CanvasView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CanvasView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    int itemWidht = 200;
    int itemHeight = 100;
    int mRadius = 400;
    int mCenterX = 100;
    int mCenterY = 500;
    private List<Point> mPointOldList;
    private final float ITEM_ANGLE = 30;
    private List<Point> mPointList;
    private RectF mRectF;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getSuggestedMinimumWidth();
        int height = getSuggestedMinimumHeight();
        setMeasuredDimension(measureWidth(width, widthMeasureSpec), measureHeight(height, heightMeasureSpec));
    }

    private int measureWidth(int defaultSize, int measureSpec) {
        int result = defaultSize;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);
        switch (mode) {
            case MeasureSpec.EXACTLY:
                result = size;
                break;
            case MeasureSpec.AT_MOST:
                result = mRadius * 2 + getPaddingRight() + getPaddingLeft();
                break;
            case MeasureSpec.UNSPECIFIED:
                result = Math.max(defaultSize, size);
                break;
            default:
                break;
        }
        return result;
    }

    private int measureHeight(int defaultSize, int measureSpec) {
        int result = defaultSize;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);
        switch (mode) {
            case MeasureSpec.EXACTLY:
                result = size;
                break;
            case MeasureSpec.AT_MOST:
                result = mRadius * 2;
                break;
            case MeasureSpec.UNSPECIFIED:
                result = Math.max(defaultSize, size);
                break;
            default:
                break;
        }
        return result;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mCenterX = getWidth() / 2;
        mCenterY = getHeight() / 2;
        mRectF = new RectF(mCenterX - mRadius, mCenterY - mRadius, mCenterX + mRadius, mCenterY + mRadius);
        onLayoutPointOld();
        onLayoutPointMove();
    }

    private void onLayoutPointMove() {
        if (mPointList == null) {
            mPointList = new ArrayList<>();
            mPointList.addAll(mPointOldList);
        }
        int count = 0;
        Log.i(TAG, " start");
        while (count < 1) {
            for (Point point : mPointList) {
                Point pointMove = MathUtil.getPointEndOfArcOnCircle(point, mCenterX, mCenterY, mRadius, mTmpAngle);
                point.x = pointMove.x;
                point.y = pointMove.y;
            }
            count++;
        }
        Log.i(TAG, "end");
    }

    private void onLayoutPointOld() {
        mPointOldList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Point point = new Point((int) (mCenterX + mRadius * Math.sin(Math.toRadians(30))), (int) (mCenterY - mRadius * Math.cos(Math.toRadians(60))));
            float angle = ITEM_ANGLE * (i - 2);
            double sin = Math.sin(Math.toRadians(angle));
            point.y = (int) (mCenterY + mRadius * sin);
            point.x = (int) (mCenterX - Math.sqrt(Math.pow(mRadius, 2) - Math.pow(point.y - mCenterY, 2)));
            mPointOldList.add(point);
        }
        Collections.sort(mPointOldList, (o1, o2) -> Integer.compare(o1.y, o2.y));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawCircle(canvas);
        drawItem(canvas);
        drawTxt(canvas);
        drawRect(canvas);
    }

    private void drawRect(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(ColorUtil.randomColor());
        canvas.drawRect(950, 250, 1050, 300, paint);
    }

    private void drawTxt(Canvas canvas) {
        //文本区域
        Rect rect = new Rect();
        rect.left = 100;
        rect.top = 100;
        rect.right = 500;
        rect.bottom = 200;
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(ColorUtil.randomColor());
        canvas.drawRect(rect, paint);
        //换行文本绘制
        String text = "这是一个长文本，可能需要换行处理.";
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.BLACK);
        textPaint.setAntiAlias(true);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setTextSize(35f);
        textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
        //过期用法
//        StaticLayout layout = new StaticLayout(text, textPaint,
//                rect.right - rect.left, //layout的宽度，字符串长度超出给定宽度时自动换行。
//                Layout.Alignment.ALIGN_NORMAL, //对齐方式
//                1.0F, //相对行间距，相对字体大小，1.0f表示行间距为1.0倍的字体高度。
//                0.0F, //在基础行距上添加多少实际行间距等于这两者的和。
//                true);
        //新的用法
        StaticLayout.Builder builder = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint,
                rect.right - rect.left);
        StaticLayout layout = builder.setAlignment(Layout.Alignment.ALIGN_NORMAL).build();
        canvas.save();
        //从100，100开始画
        canvas.translate(rect.left, rect.top);
        layout.draw(canvas);
        canvas.restore();//别忘了restore

    }

    private void drawItem(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(2f);
        Paint paintTxt = new Paint();
        paintTxt.setStyle(Paint.Style.FILL);
        paintTxt.setTextSize(25f);
        paintTxt.setAntiAlias(true);
        for (Point point : mPointList) {
            int color = ColorUtil.randomColor();
            paintTxt.setColor(color);
            paint.setColor(color);
            canvas.drawCircle(point.x, point.y, 5, paint);
            String text = point.x + "," + point.y;
            Rect rectText = new Rect();
            paintTxt.getTextBounds(text, 0, text.length(), rectText);
            if (point.x < mCenterX) {
                canvas.drawText(text, point.x - paintTxt.measureText(text), point.y, paintTxt);
            } else {
                canvas.drawText(point.x + "," + point.y, point.x, point.y, paintTxt);
            }
            //绘制扇形
            canvas.drawArc(mRectF, MathUtil.getAngleToY(point.x, point.y, mCenterX, mCenterY) - 90,
                    ITEM_ANGLE, true, paint);
        }

    }

    private void drawBitmap(Canvas canvas) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.football, options);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        Rect dst = new Rect(100, 100, 400, 400);
        canvas.drawBitmap(bitmap, null, dst, paint);
    }


    private void drawCircle(Canvas canvas) {
        Paint paintCircle = new Paint();
        paintCircle.setStyle(Paint.Style.STROKE);
        paintCircle.setColor(Color.BLUE);
        paintCircle.setTextSize(1f);
//        canvas.rotate(45);
        canvas.drawCircle(mCenterX, mCenterY, mRadius, paintCircle);
        canvas.drawLine(mCenterX - mRadius, mCenterY, mCenterX + mRadius, mCenterY, paintCircle);
        canvas.drawLine(mCenterX, mCenterY - mRadius, mCenterX, mCenterY + mRadius, paintCircle);
        paintCircle.setTextSize(25f);
        canvas.drawText(mCenterX + "," + mCenterY, mCenterX, mCenterY, paintCircle);
        canvas.drawText(MathUtil.ticket("七星彩"), mCenterX - 100, mCenterY + mRadius + 50, paintCircle);
    }

    /**
     * 记录上一次的x，y坐标
     */
    private float mLastX;
    private float mLastY;

    /**
     * 检测按下到抬起时旋转的角度,向上为负，向下为正
     */
    private double mTmpAngle = 0;
    private float mDownX = 0;
    private float mDownY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastX = event.getX();
                mLastY = event.getY();
                mDownX = event.getX();
                mDownY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                double start = MathUtil.getAngleToY(mLastX, mLastY, mCenterX, mCenterY);
                double end = MathUtil.getAngleToY(event.getX(), event.getY(), mCenterX, mCenterY);
                mTmpAngle = end - start;
                Log.i(TAG, "start=" + start + ",end=" + end + ",tempAngle=" + mTmpAngle);
                // 重新布局
                if (mTmpAngle != 0) {
                    requestLayout();
                    invalidate();
                }
                mLastX = event.getX();
                mLastY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                // 计算，每秒移动的角度
//                float anglePerSecond = mTmpAngle * 1000
//                        / (System.currentTimeMillis() - mDownTime);
//
//                // Log.e("TAG", anglePrMillionSecond + " , mTmpAngel = " +
//                // mTmpAngle);
//
//                // 如果达到该值认为是快速移动
//                if (Math.abs(anglePerSecond) > mFlingableValue && !isFling) {
//                    // post一个任务，去自动滚动
//                    post(mFlingRunnable = new AutoFlingRunnable(anglePerSecond));
//
//                    return true;
//                }
//
//                // 如果当前旋转角度超过NOCLICK_VALUE屏蔽点击
//                if (Math.abs(mTmpAngle) > NOCLICK_VALUE) {
//                    return true;
//                }
                break;
            default:
                break;
        }
        return true;
    }


    private void startAlphaAnimation(float startAlpha, float endAlpha) {
        Animation animation = new AlphaAnimation(startAlpha, endAlpha);
        startAnimation(animation);
    }
}
